import request from '@/utils/request'
import Sortable from 'sortablejs'
import { downloadUrl } from 'download.js'

export default {
  //el-table右键点击事件
  rightBtn: function(row, column, event, that, ref) {
    window.event.returnValue = false
    row.flag = true
    let selection = that.$refs[ref].selection
    that.$refs[ref].toggleRowSelection(row, row.flag)
    // if (selection.length > 1) {
    //   that.$refs[ref].clearSelection();
    //   that.$refs[ref].toggleRowSelection(selection.pop());
    // }
    var menu = that.$refs.exportMenu || document.querySelector('#exportMenu')
    menu.style.left = event.clientX + 10 + 'px'
    menu.style.top = event.clientY - 10 + 'px'
    // menu.style.display = 'block';
    that.exportMenu = true
    document.addEventListener('click', function() {
      // menu.style.display = 'none';
      that.exportMenu = false
      document.removeEventListener('click', function() {
      })
    }) // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
  },

  //序号
  serialNumber: function(row, queryParams) {
    return (queryParams.pageNum - 1) * queryParams.pageSize + row.$index + 1
  },

  //序号
  tableSerialNumber: function(row, pageNum, pageSize) {
    return (pageNum - 1) * pageSize + row.$index + 1
  },

  //添加监听页面滚动,弹框相对滚动
  mounteds: function(that) {
    // var h = 0
    if (!that.scrollTop) {
      that.scrollTop = '50px'
      // h = 50
    }
    // var appMain = document.getElementById('app-main')
    // if (appMain) {
    //   appMain.addEventListener('scroll', function() {
    //     that.scrollTop = appMain.scrollTop + h
    //     that.scrollTop += 'px'
    //   })
    // }
  },

  //移除监听页面滚动,弹框相对滚动
  destroyeds: function() {
    // var appMain = document.getElementById('app-main')
    // if (appMain){
    //   appMain.removeEventListener('scroll', function() {
    //   })
    // }
  },

  //帮助页面
  openHelp: function(that, url) {
    let routeData = that.$router.resolve({
      path: url
    })
    window.open(routeData.href, '_blank')
  },

//选择导出字段
  exportFiles(num, that, ref) {
    if (num == 1) {
      if (that.$refs[ref].selection.length < 1) {
        that.$message({
          message: '未选中数据，请选择',
          type: 'warning'
        })
        return
      }
    }
    that.exportFile = true
    that.queryParams.exprotDataSize = num
    that.queryParams.exportColumnName = []
    that.queryParams.exportCheckData = []
    that.checkAll = false
    that.isIndeterminate = false
  },
  //导出字段全选
  handleCheckAllChange(val, that, codeAll) {
    that.queryParams.exportColumnName = val ? codeAll : []
    that.isIndeterminate = false
  },
  //导出字段选择变化
  handleCheckedCitiesChange(val, that, codeAll) {
    let checkedCount = val.length
    that.checkAll = checkedCount === codeAll.length
    that.isIndeterminate = checkedCount > 0 && checkedCount < codeAll.length
  },
  //导出取消置空
  closeExportFile(that) {
    that.queryParams.exprotDataSize = null
    that.queryParams.exportColumnName = []
    that.queryParams.exportCheckData = []
  },
  //导出
  handleExport(that, ref, list, id, func) {
    if (that.queryParams.exportColumnName == 0) {
      that.$message({
        message: '请选择要导出的列',
        type: 'warning'
      })
      return
    }
    var information = '是否确认导出所有数据项？'
    if (that.queryParams.exprotDataSize == 1) {
      that.queryParams.exportCheckData = that.$refs[ref].selection.map(item => {
        if (item.sub01 && item.sub01.length != 0) {
          return { exportid: item[id], exportsubid: item.sub01[0].subid }
        } else {
          return { exportid: item[id], exportsubid: null }
        }
      })
      information = '是否确认导出选中数据项？'
    } else if (that.queryParams.exprotDataSize == 2) {
      that.queryParams.exportCheckData = list.map(item => {
        if (item.sub01 && item.sub01.length != 0) {
          return { exportid: item[id], exportsubid: item.sub01[0].subid }
        } else {
          return { exportid: item[id], exportsubid: null }
        }
      })
      information = '是否确认导出本页数据项？'
    }
    const queryParams = that.queryParams
    var loading
    that.$confirm(information, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(function() {
      loading = that.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return func(queryParams)
    }).then(response => {
      downloadUrl(response.msg, request.baseURL + '/common/download?fileName=' + response.msg + '&delete=true')
      // that.download(response.msg);
      loading.close()
      that.exportFile = false
    }).catch(err => {
      loading.close()
    })
  },
  
  //单据赋予默认值
  defaultValue(that) {
    if (that.formDefaultValue != null && that.formDefaultValue != []) {
      for (let i = 0; i < that.formDefaultValue.length; i++) {
        if (that.formDefaultValue[i].controltype == 'C') {
          that.form[that.formDefaultValue[i].code] = []
        }
        if (that.formDefaultValue[i].defaultKey != null && that.formDefaultValue[i].defaultKey != undefined && that.formDefaultValue[i].defaultKey != '') {
          that.form[that.formDefaultValue[i].code] = that.formDefaultValue[i].defaultvalue
          that.form[that.formDefaultValue[i].code + 'Name'] = that.formDefaultValue[i].defaultKey
        }
        if (that.optsObj) {
          that.optsObj[that.formDefaultValue[i].code] = that.formDefaultValue[i].opts
        }
      }
    }
  },
  //行拖拽
  rowDrop(that, ref, name) {
    var names = name.split('.')
    const tbody = that.$refs[ref].$el.querySelector('.el-table__body-wrapper tbody')
    if (names.length == 1) {
      Sortable.create(tbody, {
        handle: '.cannotDrag',
        onEnd({ newIndex, oldIndex }) {
          const currRow = that[name].splice(oldIndex, 1)[0]
          that[name].splice(newIndex, 0, currRow)
        }
      })
    } else {
      Sortable.create(tbody, {
        handle: '.cannotDrag',
        onEnd({ newIndex, oldIndex }) {
          const currRow = that[names[0]][names[1]].splice(oldIndex, 1)[0]
          that[names[0]][names[1]].splice(newIndex, 0, currRow)
        }
      })
    }

  },
  //列拖拽
  columnDrop(that, ref, name, num) {
    const i = num || 2
    const wrapperTr = that.$refs[ref].$el.querySelector('.el-table__header-wrapper tr')
    that.sortable = Sortable.create(wrapperTr, {
      animation: 180,
      delay: 0,
      filter: '.cannotDrag',
      draggable: '.canDrag',
      onEnd: evt => {
        var j = that.hideMeta.length > 0 ? i + 1 : i
        const oldItem = that[name].splice(evt.oldIndex - j, 1)[0]
        that[name].splice(evt.newIndex - j, 0, oldItem)
      }
    })
  },

  //消除改变列宽产生的bug
  headerDragend(newWidth, oldWidth, column, event, that, ref, name, num) {
    var classVal = document.getElementsByClassName(column.id)[0].getAttribute('class')
    classVal = classVal.replace('sortable-chosen', '')
    classVal = classVal.replace('sortable-ghost', '')
    classVal = classVal.replace('noclick', '')
    document.getElementsByClassName(column.id)[0].setAttribute('class', classVal)
    that.sortable.destroy()
    this.columnDrop(that, ref, name, num)
  },

  //计算属性,单据重新分组
  pages(rows, num = 2) {
    const pages = []
    var a = 0
    rows.forEach((item, index) => {
      var isShow = true
      if (item.fvisible == 'N') {
        isShow = false
        a++
      }
      const page = Math.floor((index - a) / num)
      if (isShow) {
        if (!pages[page]) {
          pages[page] = []
        }
        pages[page].push(item)
      }

    })
    return pages
  },

  //js帮助方法
  formEvent(item, row, scope, that) {
    if (this.disabledShow(row, that)) {
      return
    }
    if (scope !== undefined && scope != null) {
      that.$index = scope.$index
    }
    if (item != undefined && item != null && item != '') {
      item = item.replace(/\s/g, '')
      var funName = item.split('(')[0]
      const params = item.split('(')[1].split(')')[0].split(",#")
      const params1 = params[0]?.replace(/,(?=\[)/g, '##').split('##')
      const params2 = params[1]
      this[funName](params1[0], eval('(' + params1[1] + ')'), eval('(' + params1[2] + ')'), that, params2)
    }
  },
  openDialog(init, dst, src, that, others = null) {
    that.dst = dst || []
    that.src = src || []
    switch (init) {
      case '1': {
        //打开组织机构弹框
        that.organization = true
        // 组织弹框配置的其他参数
        if(others){
          this.otherParamsHandle(init, that, others)
        }
        break
      }
      case '2': {
        //打开角色管理弹框
        that.roleList = true
        that.materielIsShow = false
        break
      }
      case '51': {
        //打开角色框
        that.roles = true
        break
      }
      case '104': {
        //打开多选用户弹框
        that.userList2 = true
        break
      }

    }
  },
  // 单据设计中“选项列表值”配置的参数，以#开始为“其余参数”，可争对不同的弹框配置的传参做处理
  // 例如：计划工单的单据设计中，选项列表值配置了openDialog(1,['branchcode','name'],['branchcode','branchcodeName'],#{'nodeCanSelect':{'orgType':['90','70']}})
  // #号后面的参数表示其他参数，在组织弹框中做的处理如下方法：设置可选节点，orgType为‘90’或‘70’的节点可选
  otherParamsHandle(init, that, others){
    if (!others) {
      return
    }
    switch(init) {
      case '1':
        // 组织弹框配置的其他参数
        const othersObj = eval(`(${others})`)
        const { nodeCanSelect } = othersObj || {}
        // 控制组织选择框哪些节点可选（单据设计），但若代码中写入了orgNodeDisabledCallback，则单据设计的配置失效
        if(nodeCanSelect && !that.datas.orgNodeDisabledCallback){
          const keys = Object.keys(nodeCanSelect)
          that.datas.orgNodeDisabledCallback = function(data){
            for(let i=0;i<keys.length;i++){
              if(nodeCanSelect[keys[i]].includes(data[keys[i]])){
                return false
              }
            }
            return true
          }
        }
        break
      default:
        break
    }
  },

  //关闭组织机构弹框触发的方法
  closeOrganization(list, that, isShow) {
    this.assignment(list, that, isShow)
    that.organization = false
  },
  //关闭角色管理弹框触发的方法
  closeRole(list, that) {
    this.assignment(list, that)
    that.roleList = false
  },

  /** 角色弹窗 */
  closeRoles(list, that) {
    this.assignment(list, that)
    if (that.$parent.closeRoles) {
      that.$parent.closeRoles(list, that)
    }
    that.roles = false
  },
  //关闭物料档案弹框触发的方法
  closeProcessstations(list, that) {
    this.assignment(list, that)
    that.processstations = false
  },
  // 关闭多选用户弹框
  closeUserList2(list, that) {
    this.assignment(list, that)
    that.userList2 = false
  },

  //关闭弹框赋值公共方法
  assignment(list, that, isShow) {
    if (that.setTemplate) {
      if (that.$refs.parser) {
        this.getFormData(that.form,that.$refs.parser[that.$refs.parser.formConf.formModel])
      }
    }
    var formName = that.formName ? that.formName : 'form';
    if (!isShow) {
      if (that.$index != null) {
        if (list !== undefined && list !== null) {
          for (let i = 0; i < that.dst.length; i++) {
            that[formName][that.activeName][that.$index][that.src[i]] = null
            for (let z = 0; z < list.length; z++) {
              if (z === 0) {
                that[formName][that.activeName][that.$index][that.src[i]] = list[z][that.dst[i]]
              } else {
                that[formName][that.activeName][that.$index][that.src[i]] += ',' + list[z][that.dst[i]]
              }
            }
          }
        }
        that.$index = null
      } else {
        if (list !== undefined && list !== null) {
          for (let i = 0; i < that.dst.length; i++) {
            that[formName][that.src[i]] = null
            for (let z = 0; z < list.length; z++) {
              if (z === 0) {
                that[formName][that.src[i]] = list[z][that.dst[i]]
              } else {
                that[formName][that.src[i]] += ',' + list[z][that.dst[i]]
              }
            }
          }
        }
      }
    } else {
      if (list !== undefined && list !== null) {
        for (let i = 0; i < that.dst.length; i++) {
          var srcList = that.src[i].split('.')
          switch (srcList.length) {
            case 1 : {
              that[srcList[0]] = null
              for (let z = 0; z < list.length; z++) {
                if (z === 0) {
                  that[srcList[0]] = list[z][that.dst[i]]
                } else {
                  that[srcList[0]] += ',' + list[z][that.dst[i]]
                }
              }
              break
            }
            case 2 : {
              that[srcList[0]][srcList[1]] = null
              for (let z = 0; z < list.length; z++) {
                if (z === 0) {
                  that[srcList[0]][srcList[1]] = list[z][that.dst[i]]
                } else {
                  that[srcList[0]][srcList[1]] += ',' + list[z][that.dst[i]]
                }
              }
              break
            }
            case 3 : {
              that[srcList[0]][srcList[1]][srcList[2]] = null
              for (let z = 0; z < list.length; z++) {
                if (z === 0) {
                  that[srcList[0]][srcList[1]][srcList[2]] = list[z][that.dst[i]]
                } else {
                  that[srcList[0]][srcList[1]][srcList[2]] += ',' + list[z][that.dst[i]]
                }
              }
              break
            }
            default : {
              this.$message({
                message: '最多支持三级数据嵌套',
                type: 'warning'
              })
            }
          }

        }
      }
    }
    if (that.setTemplate) {
      this.setTemplate(that)
    }
  },

  //工单赋值方法
  setTemplate(that) {
    // let obj = new Object();
    // let length = that.src.length;
    // for (let i = 0; i < length; i++) {
    //   obj[that.src[i]] = that.form[that.src[i]];
    // }
    this.fillFormData(that.formData.fields, that.form)
    that.key = +new Date()
  },

  //判断输入框是否只读
  disabledShow(row, that) {
    if (that.datas && that.datas.disabled){
      return true
    }
    if (that.datas && that.datas.workShow && !that.datas.allowEdit) {
      if (that.datas && that.datas.btnShow == false) {
        return true
      }
      if (that.form.processState == 2) {
        return true
      }
    }

    // var ishow = true
    // if (that.workflow != null && that.workflow.length > 0) {
    //   for (let i = 0; i < that.workflow.length; i++) {
    //     if (that.workflow[i].name === row.code) {
    //       ishow = false
    //       if (that.workflow[i].writable) {
    //         return true
    //       } else {
    //         return false
    //       }
    //     }
    //   }
    // }
    // if (ishow) {
    //   if (row.prop6 == 'Y') {
    //     return true
    //   } else {
    //     return false
    //   }
    // }

    if (row.prop6 == 'Y') {
      return true
    } else {
      return false
    }
  },

  //判断字段是否显示
  fvisibleShow(row) {
    var ishow = true
    if (ishow) {
      if(row.fvisible == 'N') {
        return false;
      } else {
        return true;
      }
    }
    return true

  },

  //值转换
  handleList(rows) {
    let arr = []
    if (!rows) {
      rows = []
    }
    (rows instanceof Array) ? arr = rows : arr.push(rows)
    for (let i = 0; i < arr.length; i++) {
      // if (arr[i].dept != undefined) {
      //   let dept = arr[i].dept.map;
      //   if (dept != {} && dept != undefined && dept != null) {
      //     let keyArr = Object.keys(dept);
      //     for (let j = 0; j < keyArr.length; j++) {
      //       arr[i][keyArr[j]] = dept[keyArr[j]];
      //     }
      //   }
      // }
      // if (arr[i].user != undefined) {
      //   let user = arr[i].user.map;
      //   if (user != {} && user != undefined && user != null) {
      //     let keyArr = Object.keys(user);
      //     for (let j = 0; j < keyArr.length; j++) {
      //       arr[i][keyArr[j]] = user[keyArr[j]];
      //     }
      //   }
      // }
      //
      // if (mainList != undefined && subList != undefined) {
      //   for (let x = 0; x < subList.length; x++) {
      //     if (arr[i][subList[x].code] != undefined) {
      //       if (arr[i][subList[x].code].length > 0) {
      //         let subObj = arr[i][subList[x].code][0];
      //         let keyArr = Object.keys(subObj);
      //         for (let y = 0; y < mainList.length; y++) {
      //           if (keyArr.indexOf(mainList[y].code) > -1) {
      //             arr[i][mainList[y].code] = subObj[mainList[y].code];
      //           }
      //         }
      //       }
      //     }
      //   }
      // }
      for (let key in arr[i].map) {
        arr[i][key] = arr[i].map[key]
      }
    }

    return (rows instanceof Array) ? arr : arr[0]
  },

  //表单校验
  verification(row, rules, customRules, that) {
    if (!that.rules[row.code]) {
      that.rules[row.code] = []
    }
    if (rules != null && rules != undefined && rules != '') {
      var rulleArr = rules.split('&&')
      for (let i = 0; i < rulleArr.length; i++) {
        switch (rulleArr[i]) {
          case 'NotNull' : {
            //不能为空
            if (that.rules[row.code].length == 0 || (that.rules[row.code][0].required != true && that.rules[row.code][0].required != false)) {
              var msg;
              if (row.controltype == 'TS' ||　row.controltype == 'S' || row.controltype == 'E'){
                msg = '请选择'
              }else{
                msg = '请输入'
              }
              that.rules[row.code][0]={ required: true, message: msg + row.name, trigger: ['blur', 'change'] }
            }
            break
          }
          case 'MoreZero' : {
            //大于零
            that.rules[row.code].push({
              max_age: 0, validator: function(rule, value, callback) {
                if (value == '' || value == null) {
                  callback()
                } else if (value < rule.max_age) {
                  callback(new Error(row.name + '必须大于等于0'))
                } else {
                  callback()
                }
              }, trigger: ['blur', 'change']
            })
            break
          }
          case 'Number' : {
            //数字（整数或小数）
            that.rules[row.code].push({
              validator: function(rule, value, callback) {
                let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g
                if (value == '' || value == null) {
                  callback()
                } else if (!reg.test(value)) {
                  callback(new Error('请输入数字'))
                } else {
                  callback()
                }
              }, trigger: ['blur', 'change']
            })
            // that.rules[row.code].push({type: 'number', message: row.name+"必须为数字", trigger: ['blur', 'change']});
            break
          }
          case 'Int' : {
            //整数
            that.rules[row.code].push({
              validator: function(rule, value, callback) {
                let reg = /^-?[1-9]\d*$/g
                if (value == '' || value == null) {
                  callback()
                } else if (!reg.test(value)) {
                  callback(new Error('请输入整数'))
                } else {
                  callback()
                }
              }, trigger: ['blur', 'change']
            })
            break
          }
          case 'Email' : {
            that.rules[row.code].push({ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] })
            break
          }
          case 'ZipCode' : {
            //邮政编码（中国）
            that.rules[row.code].push({
              validator: function(rule, value, callback) {
                let reg = /^(0[1-7]|1[0-356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[0-5]|8[013-6])\d{4}$/g
                if (value == '' || value == null) {
                  callback()
                } else if (!reg.test(value)) {
                  callback(new Error('请输入正确的邮政编码'))
                } else {
                  callback()
                }
              }, trigger: ['blur', 'change']
            })
            break
          }
          case 'CnTel' : {
            //固定电话号码（中国）
            that.rules[row.code].push({
              validator: function(rule, value, callback) {
                let reg = /^(0[1-9]{2})-\d{8}$|^(0[1-9]{3}-(\d{7,8}))$/g
                if (value == '' || value == null) {
                  callback()
                } else if (!reg.test(value)) {
                  callback(new Error('请输入正确的固定电话号码'))
                } else {
                  callback()
                }
              }, trigger: ['blur', 'change']
            })
            break
          }
          case 'CnMobile' : {
            //移动电话号码（中国）
            that.rules[row.code].push({
              validator: function(rule, value, callback) {
                let reg = /^1[34578]\d{9}$/g
                if (value == '' || value == null) {
                  callback()
                } else if (!reg.test(value)) {
                  callback(new Error('请输入正确的移动电话号码'))
                } else {
                  callback()
                }
              }, trigger: ['blur', 'change']
            })
            break
          }
          case 'CnPhone' : {
            //固定或移动电话号码（中国）
            that.rules[row.code].push({
              validator: function(rule, value, callback) {
                let reg1 = /^(0[1-9]{2})-\d{8}$|^(0[1-9]{3}-(\d{7,8}))$/g
                let reg2 = /^1[34578]\d{9}$/g
                if (value == '' || value == null) {
                  callback()
                } else if (!reg1.test(value) && !reg2.test(value)) {
                  callback(new Error('请输入正确的固定或移动电话号码'))
                } else {
                  callback()
                }
              }, trigger: ['blur', 'change']
            })
            break
          }
          case 'IDCardNo' : {
            //身份证号码（中国）
            that.rules[row.code].push({
              validator: function(rule, value, callback) {
                let reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/
                if (value == '' || value == null) {
                  callback()
                } else if (!reg.test(value)) {
                  callback(new Error('请输入正确的身份证号码'))
                } else {
                  callback()
                }
              }, trigger: ['blur', 'change']
            })
            break
          }
        }
      }
    }

    if (customRules != null && customRules != undefined && customRules != '') {
      that.rules[row.code].push({
        validator: function(rule, value, callback) {
          let reg = eval(customRules.split('","show":"')[0].replace(/{"reg":"/g, ''))
          let show = customRules.split(',"show":"')[1].split('","title":')[0]
          let title = customRules.split('"title":"')[1].replace(/"}/g, '')
          if (value == '' || value == null) {
            callback()
          } else {
            if (show == 'true') {
              if (!reg.test(value)) {
                callback(new Error(title))
              } else {
                callback()
              }
            } else {
              if (reg.test(value)) {
                callback(new Error(title))
              } else {
                callback()
              }
            }
          }
        }, trigger: ['blur', 'change']
      })
    }
  },

//子表合计
  getSummaries(param, that) {
    param.data = param.data || []
    const { columns, data } = param
    const sums = []
    var subList
    for (var i = 0; i < that.initSubList.length; i++) {
      if (that.initSubList[i].code == that.activeName) {
        subList = that.initSubList[i].list
      }
    }
    if (subList && subList.length > 0) {
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index > 2) {
          const values = data.map(item => Number(item[column.property]))
          if (subList[index - 3] && subList[index - 3].prop7 == 'Y') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              for (let u = 3; u < sums.length; u++) {
                if (sums[u]) {  //判断sums[u]是否有值
                  sums[u] = Math.round(sums[u] * 100) / 100  //可以对精度进行控制，保留两位小数点
                  //如果是想保留三位小数 100改为1000即可
                }
              }
            } else {
              sums[index] = 'N/A'
            }
          }
        }
      })
    }
    return sums
  }
  ,

//子表回车自动选中下一行input
  nextFocus(activeName, i, j, scope, that) {
    if (that.form[activeName].length == scope.$index + 1) {
      that.focusIndex = activeName + i + j + 0
    } else {
      var index = scope.$index + 1
      that.focusIndex = activeName + i + j + index
    }
  }
  ,
  Focus(activeName, i, j, scope, that) {
    that.focusIndex = activeName + i + j + scope.$index
  }
  ,

//栅格列数
  elSpan(nummber) {
    var num = 24 / nummber - 1
    return num
  }
  ,
//偏移数
  offsetSpan(index, nummber) {
    var num = index % nummber == 0 ? 0 : 1
    return num
  }
  ,

  getDicts(type, data, that) {
    var datas = data.split('.')
    if (datas.length == 1) {
      if (that[data].length == 0) {
        request({
          url: '/system/crccode/listByDict/' + type,
          method: 'get'
        }).then(response => {
          that[data] = response.data
        })
      }
    } else {
      if (that[datas[0]][datas[1]].length == 0) {
        request({
          url: '/system/crccode/listByDict/' + type,
          method: 'get'
        }).then(response => {
          that[datas[0]][datas[1]] = response.data
        })
      }
    }

  }
  ,

  getTreeOption(url, data, that) {
    var datas = data.split('.')
    if (datas.length == 1) {
      if (that[data].length == 0) {
        request({
          url: url,
          method: 'get'
        }).then(response => {
          that[data] = response.data
        })
      }
    } else {
      if (that[datas[0]][datas[1]].length == 0) {
        request({
          url: url,
          method: 'get'
        }).then(response => {
          that[datas[0]][datas[1]] = response.data
        })
      }
    }

  }
  ,

//模板数据回显
  fillFormData(fields, data) {
    fields.forEach(item => {
      if (item.__vModel__) {
        const val = data[item.__vModel__]
        item.__config__.defaultValue = val
      } else {
        if (item.__config__.children && item.__config__.children.length > 0) {
          this.fillFormData(item.__config__.children, data)
        }
      }
    })
  }
  ,

//模板数据放进form内;
  getFormData(form, data) {
    for (var key in data) {
      form[key] = data[key]
    }
  }
  ,

//表格树父子关联
  rowSelect(selection, rows, ref, that) {
    rows.isSelect = !rows.isSelect
    this.toggleSelection([rows], rows.isSelect, ref, that)
  }
  ,

  selectAll(selection, dataName, ref, that) {
    that.isAllSelect = !that.isAllSelect
    this.toggleSelection(that[dataName], that.isAllSelect, ref, that)
  }
  ,
  toggleSelection(rows, show, ref, that) {
    rows.map(el => {
      el.isSelect = show
      that.$refs[ref].toggleRowSelection(el, show)
      if (el.children && el.children.length > 0) {
        this.toggleSelection(el.children, show, ref, that)
      }
    })
  }
  ,

//流程状态
  processState(row,code) {
    if (code == 'processState'){
      if (row.processState == 1) {
        if (row.isHangup == 'Y') {
          return { info: 'warning', name: '挂起中' }
        }
        return { info: 'success', name: '进行中' }
      } else if (row.processState == 2) {
        return { info: 'danger', name: '已结束' }
      } else {
        return { info: 'primary', name: '未开始' }
      }
    }else if (code == 'processStateName'){
      if (row.processStateName == '未开始') {
        return { info: 'primary', name:row.processStateName}
      } else if (row.processStateName == '已结束') {
        return { info: 'danger', name: row.processStateName }
      } else {
        return { info: 'success', name: row.processStateName }
      }
    }else if(code == 'routeflagName') {
      if (row.routeflagName == '停机') {
        return { info: 'primary', name:row.routeflagName}
      } else {
        return { info: 'success', name: row.routeflagName }
      }
    }

  },
  randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = $chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },

  querySearchAsync(queryString, callback,item, row, that){
      // console.log(queryString, callback,item, row, that)
    if (queryString && item  ) {
      item = item.replace(/\s/g, '')
      item = item.replace(/,\[/g, ',,[').split(',,')
      that.dst = eval('(' + item[1] + ')') || []
      that.src = eval('(' + item[2] + ')') || []
      request({
        url: eval('(' + item[0] + ')'),
        method: 'POST',
        data:{
          searchValue:queryString
        }
      }).then(res => {
        callback(res || [])
      }).catch(err => {
        callback([])
      })
    }else{
      callback([])
    }
  },

  handleSelect(item,that){
    this.assignment([item], that)
  },

  /**
   * 像素转换成rem（postcss-pxtorem）
   * @param {*} pix
   * @returns
   */
  pxToRem(pix, hasUnit=true) {
    const _pix = Number(pix);
    if(hasUnit){
      return _pix / 16 + 'rem';
    }
    return _pix / 16;
  },

  // 获取跟元素字体
  getHtmlRootValue() {
    const width = document.body.offsetWidth;
    if (width <= 1280) {
        return 12;
    } else if (width <= 1366) {
        return 12;
    } else if (width <= 1679) {
        return 14;
    } else if (width <= 1920) {
        return 16;
    } else if (width <= 2300) {
        return 18;
    } else if (width <= 2700) {
        return 22;
    } else if (width <= 3199) {
        return 26;
    } else if (width >= 3200) {
        return 18;
    }
    return 16;
  },

  /**
   * 像素转换成当前自适应的px（postcss-pxtorem）
   * @param {*} pix
   * @param {*} type 返回的字符类型
   * @returns
   */
  pxToFixPx(pix, type='string', min=0) {
    const remNum = this.pxToRem(pix, false)
    const root = this.getHtmlRootValue()
    const value = root * remNum
    if(type.toLocaleLowerCase === 'string') {
      return value < min ? min : value.toString()
    }
    return value < min ? min : value
  },
  deepMerge(opt, newOpt) {
    if (Object.prototype.toString.call(opt) === '[object Object]') {
      for (let key in newOpt) {
        if (opt[key] && (Object.prototype.toString.call(opt[key]) === '[object Object]' || Object.prototype.toString.call(opt[key]) === '[object Array]')) {
          this.deepMerge(opt[key], newOpt[key])
        } else {
          opt[key] = newOpt[key]
        }
      }
    } else if (Object.prototype.toString.call(opt) === '[object Array]') {
      for (let i = 0; i < newOpt.length; i++) {
        if (Object.prototype.toString.call(opt[i]) === '[object Object]' || Object.prototype.toString.call(opt[i]) === '[object Array]') {
          this.deepMerge(opt[i], newOpt[i])
        } else {
          opt[i] = newOpt[i]
        }
      }
    }
  },
  formatString(unixtime) {
    if(!unixtime){
      return ''
    }
    var date = new Date(unixtime);
    if(date.toString()==='Invalid Date'){
      return ''
    }
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + ' 年 ' + m + ' 月 ' + d + ' 日 ' + h + ' 时 ';//年月日时分
  },
  /**
   * 某月有多少天
   * @param {*} month 
   */
  getMonthDays(month, year){
    if (!year) {
      year = new Date().getFullYear()
    }
    let dayLen = 0
    switch (month) {
      case 2:
        if (year % 4 === 0) {
          dayLen = 29
        } else {
          dayLen = 28
        }
        break
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
        dayLen = 31
        break
      case 4:
      case 6:
      case 9:
      case 11:
        dayLen = 30
        break
      default:
        break
    }
    return dayLen
  }
}
